'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { 
  Table, TableBody, TableCell, TableHead, 
  TableHeader, TableRow 
} from '@/components/ui/table';
import { 
  Dialog, DialogContent, DialogHeader, 
  DialogTitle, DialogFooter, DialogTrigger 
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { 
  Form, FormControl, FormField, FormItem, 
  FormLabel, FormMessage 
} from '@/components/ui/form';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { 
  Search, Plus, MoreHorizontal, Edit, Trash, 
  RefreshCw, Users, CheckCircle, XCircle,
  ChevronLeft, ChevronRight
} from 'lucide-react';
import { FadeIn } from '@/components/ui/motion';
import { formatDate } from '@/lib/utils';
import { useAuth } from '@/hooks/use-auth';
import { 
  Parent,
  getParents, 
  createParent, 
  updateParent, 
  deleteParent,
  updateParentStatus,
  ParentQueryParams
} from '@/services/parentService';

// 表单验证模式
const parentFormSchema = z.object({
  username: z.string().min(3, '用户名至少3个字符'),
  name: z.string().min(2, '姓名至少2个字符'),
  email: z.string().email('请输入有效的邮箱地址'),
  phone: z.string().min(11, '请输入有效的手机号码'),
  password: z.string().min(6, '密码至少6个字符').optional(),
  confirmPassword: z.string().optional(),
}).refine((data) => {
  if (data.password && data.confirmPassword) {
    return data.password === data.confirmPassword;
  }
  return true;
}, {
  message: '两次输入的密码不一致',
  path: ['confirmPassword'],
});

type ParentFormValues = z.infer<typeof parentFormSchema>;

export default function ParentsPage() {
  const [parents, setParents] = useState<Parent[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [currentParent, setCurrentParent] = useState<Parent | null>(null);
  const [pagination, setPagination] = useState({
    page: 0,
    size: 10,
    totalPages: 0,
    totalElements: 0,
    last: false,
    first: true
  });
  const { toast } = useToast();
  const { user } = useAuth();

  // 表单初始化
  const form = useForm<ParentFormValues>({
    resolver: zodResolver(parentFormSchema),
    defaultValues: {
      username: '',
      name: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
    },
  });

  // 编辑表单初始化
  const editForm = useForm<ParentFormValues>({
    resolver: zodResolver(parentFormSchema),
    defaultValues: {
      username: '',
      name: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
    },
  });

  // 当选择编辑家长时，设置表单默认值
  useEffect(() => {
    if (currentParent && isEditDialogOpen) {
      editForm.reset({
        username: currentParent.username,
        name: currentParent.name,
        email: currentParent.email || '',
        phone: currentParent.phone || '',
        password: '',
        confirmPassword: '',
      });
    }
  }, [currentParent, isEditDialogOpen, editForm]);

  // 获取家长列表
  const fetchParents = async (params: ParentQueryParams = {}) => {
    setLoading(true);
    try {
      const { page = pagination.page, size = pagination.size, keyword = searchTerm } = params;
      const data = await getParents({ page, size, keyword });
      
      console.log('家长列表数据:', data);
      
      if (!data || !data.content) {
        console.error('API响应数据格式错误');
        setParents([]);
        setPagination({
          page: 0,
          size: 10,
          totalPages: 0,
          totalElements: 0,
          last: true,
          first: true
        });
        return;
      }
      
      // 设置家长列表和分页数据
      setParents(data.content);
      setPagination({
        page: data.pageable.pageNumber,
        size: data.pageable.pageSize,
        totalPages: data.totalPages,
        totalElements: data.totalElements,
        last: data.last,
        first: data.first
      });
    } catch (error) {
      console.error('获取家长列表失败:', error);
      toast({
        title: '获取失败',
        description: '无法获取家长列表，请稍后重试',
        variant: 'destructive',
      });
      setParents([]);
      setPagination({
        page: 0,
        size: 10,
        totalPages: 0,
        totalElements: 0,
        last: true,
        first: true
      });
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchParents();
  }, []);

  // 搜索家长
  const handleSearch = () => {
    fetchParents({ page: 0, keyword: searchTerm });
  };

  // 处理页码变化
  const handlePageChange = (newPage: number) => {
    fetchParents({ page: newPage });
  };

  // 添加家长
  const handleAddParent = async (data: ParentFormValues) => {
    try {
      setLoading(true);
      
      const result = await createParent({
        username: data.username,
        name: data.name,
        email: data.email,
        phone: data.phone,
        password: data.password || '',
        role: 'PARENT',
        enabled: true
      });
      
      console.log('添加家长结果:', result);
      
      setIsAddDialogOpen(false);
      form.reset();
      
      toast({
        title: '添加成功',
        description: `家长 ${data.name} 已成功添加`,
      });
      
      fetchParents();
    } catch (error) {
      console.error('添加家长失败:', error);
      toast({
        title: '添加失败',
        description: '无法添加家长，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 编辑家长
  const handleEditParent = async (data: ParentFormValues) => {
    if (!currentParent) return;
    
    try {
      setLoading(true);
      
      const result = await updateParent(currentParent.id, {
        name: data.name,
        email: data.email,
        phone: data.phone,
        password: data.password
      });
      
      console.log('编辑家长结果:', result);
      
      setIsEditDialogOpen(false);
      setCurrentParent(null);
      
      toast({
        title: '更新成功',
        description: `家长 ${data.name} 已成功更新`,
      });
      
      fetchParents();
    } catch (error) {
      console.error('更新家长失败:', error);
      toast({
        title: '更新失败',
        description: '无法更新家长信息，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 删除家长
  const handleDeleteParent = async () => {
    if (!currentParent) return;
    
    try {
      setLoading(true);
      
      await deleteParent(currentParent.id);
      
      setIsDeleteDialogOpen(false);
      setCurrentParent(null);
      
      toast({
        title: '删除成功',
        description: `家长 ${currentParent.name} 已成功删除`,
      });
      
      fetchParents();
    } catch (error) {
      console.error('删除家长失败:', error);
      toast({
        title: '删除失败',
        description: '无法删除家长，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  // 切换家长状态
  const toggleParentStatus = async (parent: Parent) => {
    try {
      setLoading(true);
      
      const result = await updateParentStatus(parent.id, !parent.enabled);
      
      console.log('切换家长状态结果:', result);
      
      toast({
        title: '状态更新',
        description: `家长 ${parent.name} 已${!parent.enabled ? '启用' : '禁用'}`,
      });
      
      fetchParents();
    } catch (error) {
      console.error('更新家长状态失败:', error);
      toast({
        title: '更新失败',
        description: '无法更新家长状态，请稍后重试',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <FadeIn>
      <Toaster />
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">家长管理</h1>
          <div className="flex items-center gap-4">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索家长..."
                className="pl-8 w-64"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              />
            </div>
            <Button 
              variant="outline" 
              onClick={handleSearch}
            >
              <Search className="h-4 w-4 mr-2" />
              搜索
            </Button>
            <Button 
              variant="default" 
              onClick={() => fetchParents()}
              disabled={loading}
            >
              <RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
              刷新
            </Button>
            <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="h-4 w-4 mr-2" />
                  添加家长
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                  <DialogTitle>添加家长</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                  <form onSubmit={form.handleSubmit(handleAddParent)} className="space-y-4 py-4">
                    <FormField
                      control={form.control}
                      name="username"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>用户名</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入用户名" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>姓名</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入姓名" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>邮箱</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入邮箱" type="email" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="phone"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>手机号码</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入手机号码" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>密码</FormLabel>
                          <FormControl>
                            <Input placeholder="请输入密码" type="password" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="confirmPassword"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>确认密码</FormLabel>
                          <FormControl>
                            <Input placeholder="请再次输入密码" type="password" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <DialogFooter className="pt-4">
                      <Button 
                        type="button" 
                        variant="outline" 
                        onClick={() => setIsAddDialogOpen(false)}
                      >
                        取消
                      </Button>
                      <Button type="submit" disabled={loading}>
                        {loading ? '添加中...' : '添加'}
                      </Button>
                    </DialogFooter>
                  </form>
                </Form>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>用户名</TableHead>
                  <TableHead>姓名</TableHead>
                  <TableHead>邮箱</TableHead>
                  <TableHead>手机号码</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-10">
                      <RefreshCw className="h-6 w-6 animate-spin mx-auto" />
                      <p className="mt-2 text-sm text-gray-500">加载中...</p>
                    </TableCell>
                  </TableRow>
                ) : parents.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-10">
                      <Users className="h-10 w-10 mx-auto text-gray-400" />
                      <p className="mt-2 text-gray-500">
                        {searchTerm ? '没有找到匹配的家长' : '暂无家长数据'}
                      </p>
                    </TableCell>
                  </TableRow>
                ) : (
                  parents.map((parent) => (
                    <TableRow key={parent.id}>
                      <TableCell className="font-medium">{parent.id}</TableCell>
                      <TableCell>{parent.username}</TableCell>
                      <TableCell>{parent.name}</TableCell>
                      <TableCell>{parent.email || '-'}</TableCell>
                      <TableCell>{parent.phone || '-'}</TableCell>
                      <TableCell>
                        {parent.enabled ? (
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            <CheckCircle className="w-3 h-3 mr-1" />
                            启用
                          </span>
                        ) : (
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                            <XCircle className="w-3 h-3 mr-1" />
                            禁用
                          </span>
                        )}
                      </TableCell>
                      <TableCell>{formatDate(parent.createTime)}</TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={() => {
                              setCurrentParent(parent);
                              setIsEditDialogOpen(true);
                            }}>
                              <Edit className="mr-2 h-4 w-4" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => toggleParentStatus(parent)}>
                              {parent.enabled ? (
                                <>
                                  <XCircle className="h-4 w-4 mr-2" />
                                  禁用
                                </>
                              ) : (
                                <>
                                  <CheckCircle className="h-4 w-4 mr-2" />
                                  启用
                                </>
                              )}
                            </DropdownMenuItem>
                            <DropdownMenuItem 
                              onClick={() => {
                                setCurrentParent(parent);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="text-red-600"
                            >
                              <Trash className="mr-2 h-4 w-4" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
            
            {/* 分页控件 */}
            {!loading && parents.length > 0 && (
              <div className="flex items-center justify-between px-4 py-4 border-t">
                <div className="text-sm text-gray-500">
                  共 {pagination.totalElements} 条记录，第 {pagination.page + 1} 页 / 共 {pagination.totalPages} 页
                </div>
                <div className="flex items-center space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(pagination.page - 1)}
                    disabled={pagination.first}
                  >
                    <ChevronLeft className="h-4 w-4" />
                    上一页
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(pagination.page + 1)}
                    disabled={pagination.last}
                  >
                    下一页
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 编辑家长对话框 */}
        <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>编辑家长</DialogTitle>
            </DialogHeader>
            <Form {...editForm}>
              <form onSubmit={editForm.handleSubmit(handleEditParent)} className="space-y-4 py-4">
                <FormField
                  control={editForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={editForm.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>邮箱</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入邮箱" type="email" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={editForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号码</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入手机号码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={editForm.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>密码</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入密码" type="password" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={editForm.control}
                  name="confirmPassword"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>确认密码</FormLabel>
                      <FormControl>
                        <Input placeholder="请再次输入密码" type="password" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <DialogFooter className="pt-4">
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => {
                      setIsEditDialogOpen(false);
                      setCurrentParent(null);
                    }}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={loading}>
                    {loading ? '保存中...' : '保存'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>

        {/* 删除家长确认对话框 */}
        <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <DialogContent className="sm:max-w-[400px]">
            <DialogHeader>
              <DialogTitle>确认删除</DialogTitle>
            </DialogHeader>
            <div className="py-4">
              <p>您确定要删除家长 <span className="font-semibold">{currentParent?.name}</span> 吗？此操作不可撤销。</p>
            </div>
            <DialogFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => {
                  setIsDeleteDialogOpen(false);
                  setCurrentParent(null);
                }}
              >
                取消
              </Button>
              <Button 
                type="button" 
                variant="destructive" 
                onClick={handleDeleteParent}
                disabled={loading}
              >
                {loading ? '删除中...' : '确认删除'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </FadeIn>
  );
} 